package com.jsmtr.rms.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.service.IDoSZService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jsmtr.rms.entity.vo.NZUserForm;
import com.jsmtr.rms.service.INZService;
import com.jsmtr.rms.service.IUtilService;
import com.jsmtr.rms.utils.PhoneTools;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/Do/NZEmploy")
public class DoNZEmployController {

    @Resource
    private IUtilService utilService;
    @Resource
    private INZService nzService;

    @Resource
    private IDoSZService szService;

    //[start] 查询应聘者信息

    //首页
    @RequestMapping("/")
    public String Index(HttpServletRequest request, Model model) {
        try {
            model.addAttribute("path", request.getContextPath());
            String pid = request.getParameter("pid").trim();
            String fid = request.getParameter("fid").trim();
            String deptcode = request.getParameter("deptcode").trim();

            model.addAttribute("pid", pid);
            model.addAttribute("fid", fid);
            model.addAttribute("deptcode", deptcode);

            List<BaseConfig> configs = utilService.getConfigs("dzmb");
            StringBuilder str1 = new StringBuilder();
            for (BaseConfig config : configs) {
                str1.append("<option value='" + config.getCont() + "'>" + config.getCont() + "</option>");
            }
            model.addAttribute("address", str1);

            List<BaseConfig> _configs = utilService.getConfigs("dxmb");
            StringBuilder str3 = new StringBuilder();
            for (BaseConfig _config : _configs) {
                str3.append("<option value='" + _config.getCode() + "'>" + _config.getName() + "</option>");
            }
            model.addAttribute("dxmb", str3);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Do/Internal/Employ/index";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/getusers")
    public void getusers(HttpServletRequest request, HttpServletResponse response, DUserResume user) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String flowid = request.getParameter("flowid").trim();
            user.setPath("/" + flowid + "/");

            Map<String, Object> map = nzService.getUsers(page, perpage, user);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 0;
                for (DNZResume _user : (List<DNZResume>) object) {
                    result.append("<tr><td><input type='checkbox' id='cb_" + _user.getId() + "' value='" + _user.getId() + "'></td>");
                    result.append("<td>" + (perpage * (page - 1) + num + 1) + "</td>");
                    result.append("<td>" + _user.getCode() + "</td>");
                    result.append("<td class='link'><a target='_blank' href='"
                            + request.getContextPath() + "/Do/NZApply/View?id="
                            + _user.getId() + "'>" + _user.getName()
                            + "</a></td>");
                    result.append("<td>" + _user.getTel() + "<input type='hidden' name='resume[" + num + "].id' value='" + _user.getId() + "' /></td>");
                    result.append("<td>" + (_user.getBdtime() == null ? "" : _user.getBdtime()) + "</td>");
                    result.append("<td>" + (_user.getBdaddress() == null ? "" : _user.getBdaddress()) + "</td>");
                    result.append("<td>" + (_user.getBdlxr() == null ? "" : (_user.getBdlxr() + " " + _user.getBdlxdh())) + "</td>");
                    result.append("<td>" + _user.getBdmsg() + "</td>");
                    result.append("<td><div><select name='resume[" + num + "].bdstate'>");
                    result.append("<option value='未报到'>未报到</option><option value='已报到'>已报到</option>");
                    result.append("</select><input type='hidden' value='" + _user.getBdstate() + "' /></div></td>");

                    if (_user.getBdstate() == null) {
                        result.append("<td class='true'><span>未完成</td></tr>");
                    } else {
                        if (_user.getBdstate().equals("已报到")) {
                            result.append("<td class='false'><span>已完成</td></tr>");
                        } else {
                            result.append("<td class='true'><span>未完成</td></tr>");
                        }
                    }

                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='11'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }

    }

    //[end]

    //[start] 报到安排

    @RequestMapping(value = "/PlanAction", method = RequestMethod.POST)/*HRGXUser user*/
    public void PlanAction(HttpServletRequest request, HttpServletResponse response, DUserResume _user) {
        try {
            String[] uids = request.getParameterValues("uid");
            if (uids == null) {
                utilService.printJsonResult(false, "请选择报到人员!", "no", response);
            } else {
                String pid = request.getParameter("pid").trim();//招聘方案ID
                String fid = request.getParameter("fid").trim();//招聘流程ID
                String deptcode = request.getParameter("deptcode").trim();//责任部门编码
                String bdzysx=request.getParameter("bdzysx");

                BaseUser cuser = utilService.getSessionUser(request);
                if (cuser.getUdept().equals(deptcode)) {
                    //流程是否结束
                    if (utilService.FlowIsDoing(fid)) {
                        List<DUserResume> editlist = new ArrayList<DUserResume>();
                        List<DoZysx> zysxList=new ArrayList<>();
                        List<DUserResume> users = szService.getResumes(uids);
                        for (DUserResume user : users) {
                            if (user.getFqstate().equals("未放弃")
                                    && user.getFid().equals(fid)
                                    && user.getBdmsg().equals("未发通知")
                                    && user.getNrid() == null) {
                                user.setBdtime(_user.getBdtime());
                                user.setBdaddress(_user.getBdaddress());
                                user.setBdlxr(_user.getBdlxr());
                                user.setBdlxdh(_user.getBdlxdh());
                                editlist.add(user);
                            }

                            if(bdzysx!=null&&bdzysx.trim().length()>0){
                                DoZysx zysx=new DoZysx();
                                zysx.setId(UUID.randomUUID().toString());
                                zysx.setFid(fid);
                                zysx.setPid(pid);
                                zysx.setRemark(bdzysx);
                                zysx.setUserid(user.getId());
                                zysx.setType("TJ");
                                zysx.setAddtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                zysx.setAdduser(cuser.getUcode());
                                zysxList.add(zysx);
                            }
                        }
                       /* List<DNZResume> editlist = new ArrayList<DNZResume>();
                        List<DNZResume> users = nzService.getUsers(pid, uids);

                        for (DNZResume _user : users) {
                            if (_user.getBdmsg().equals("未发通知")
                                    && _user.getFid().equals(fid)
                                    && _user.getFqstate().equals("未放弃")) {
                                _user.setBdtime(user.getBdtime());
                                _user.setBdaddress(user.getBdaddress());
                                _user.setBdlxr(user.getBdlxr());
                                _user.setBdlxdh(user.getBdlxdh());
                                editlist.add(_user);
                            }
                        }*/

                        if (editlist.size() > 0) {
                            utilService.editList(editlist);
                            utilService.printJsonResult(true, "操作成功！", "no", response);
                        } else {
                            utilService.printJsonResult(false, "当前信息不能执行此操作！", "no", response);
                        }
                    } else {
                        utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败!", "no", response);
        }
    }

    //[end]

    //[start] 发布报到通知

    @RequestMapping(value = "/MsgAction", method = RequestMethod.POST)
    public void MsgAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] uids = request.getParameterValues("uid");
            if (uids == null) {
                utilService.printJsonResult(false, "请选择报到的应聘者!", "no", response);
            } else {
                String pid = request.getParameter("pid").trim();//招聘方案ID
                String fid = request.getParameter("fid").trim();//招聘流程ID
                String deptcode = request.getParameter("deptcode").trim();//责任部门编码

                BaseUser cuser = utilService.getSessionUser(request);
                if (cuser.getUdept().equals(deptcode)) {
                    //流程是否结束
                    if (utilService.FlowIsDoing(fid)) {
                        String dxnr = request.getParameter("dxnr").trim();
                        List<Map<String, String>> msgs = new ArrayList<Map<String, String>>();

                    //    List<DNZResume> editlist = new ArrayList<DNZResume>();
                      //  List<DNZResume> users = nzService.getUsers(pid, uids);
                       /* for (DNZResume user : users) {
                            if (user.getBdmsg().equals("未发通知")
                                    && user.getFid().equals(fid)
                                    && user.getFqstate().equals("未放弃")) {
                                user.setBdmsg("已发通知");
                                editlist.add(user);

                                //-------------短信----------------
                                Map<String, String> _map = new HashMap<String, String>();
                                _map.put("tel", user.getTel());
                                _map.put("cont", dxnr.replace("{姓名}", user.getName()).replace("{时间}", user.getBdtime()).replace("{地点}", user.getBdaddress()));
                                msgs.add(_map);

                            }
                        }*/

                        List<DUserResume> editlist = new ArrayList<DUserResume>();
                        List<DUserResume> users = szService.getResumes(uids);
                        for (DUserResume user : users) {
                            if (user.getBdmsg().equals("未发通知")
                                    && user.getFid().equals(fid)
                                    && user.getFqstate().equals("未放弃")
                                    && user.getBdtime() != null
                                    && user.getNrid() == null) {
                                user.setBdmsg("已发通知");
                                editlist.add(user);

                                //-------------短信----------------
                                Map<String, String> _map = new HashMap<String, String>();
                                _map.put("tel", user.getTel());
                                _map.put("cont", dxnr.replace("{姓名}", user.getName()).replace("{时间}", user.getBdtime()).replace("{地点}", user.getBdaddress()));
                                msgs.add(_map);
                            }
                        }

                        if (editlist.size() > 0) {
                            utilService.editList(editlist);
                            BaseMessageConfig messageConfig = utilService.getMessageConfig();
                            // 发送短信
                            if (PhoneTools.sendMsg(msgs, messageConfig.getUsername(), messageConfig.getPassword(), messageConfig.getHost())) {
                                utilService.printJsonResult(true, "操作成功！", "no", response);
                            } else {
                                utilService.printJsonResult(false, "短信发送失败！", "no", response);
                            }
                        } else {
                            utilService.printJsonResult(false, "当前信息不能执行此操作！", "no", response);
                        }
                    } else {
                        utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]

    //[start] 获得短信模版内容

    @RequestMapping("/getMsg")
    public void getMsgCont(HttpServletRequest request, HttpServletResponse response) {
        try {
            String msg = utilService.getConfig(request.getParameter("code").trim());
            utilService.printTextResult(msg, response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("", response);
        }
    }

    //[end]

    //[start] 提交报到结果

    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/RAction", method = RequestMethod.POST)/*NZUserForm users*/
    public void RAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] uids = request.getParameterValues("uid");
            if (uids == null) {
                utilService.printJsonResult(false, "请选择人员！", "no", response);
            } else {
                String pid = request.getParameter("pid").trim();//招聘方案ID
                String fid = request.getParameter("fid").trim();//招聘流程ID
                String deptcode = request.getParameter("deptcode").trim();//责任部门编码
                String bdstate = request.getParameter("bdstate").trim();//报到结果
                String bdremark = request.getParameter("bdremark").trim();//报到备注

                BaseUser cuser = utilService.getSessionUser(request);
                if (cuser.getUdept().equals(deptcode)) {
                    //流程是否结束
                    if (utilService.FlowIsDoing(fid)) {
                        List editlist = new ArrayList();
                       /*  Date time = new Date();
                       for (DNZResume user : users.getResume()) {
                            DNZResume usr = nzService.getDResume(user.getId());
                            if (!usr.getBdstate().equals(user.getBdstate())
                                    && usr.getFid().equals(fid)
                                    && usr.getFqstate().equals("未放弃")) {
                                usr.setBdstate(user.getBdstate());
                                usr.setBddate(time);
                                usr.setBduid(cuser.getId());
                                usr.setBduname(cuser.getUname());

                                editlist.add(usr);
                            }
                        }*/

                        List<DUserResume> users = szService.getResumes(uids);
                        for (DUserResume user : users) {
                            if (user.getFqstate().equals("未放弃")
                                    && user.getFid().equals(fid)
                                    && user.getNrid() == null) {
                                user.setBddate(new Date());
                                user.setBdremark(bdremark);
                                user.setBdstate(bdstate);
                                user.setBduid(cuser.getId());
                                user.setBduname(cuser.getUname());

                                editlist.add(user);
                            }
                        }
                        if (editlist.size() > 0) {
                            utilService.editList(editlist);
                            utilService.printJsonResult(true, "操作成功！", "no", response);
                        } else {
                            utilService.printJsonResult(false, "当前信息不能执行此操作！", "no", response);
                        }
                    } else {
                        utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]

    @ResponseBody
    @RequestMapping(value = "/getNzEmployListLayuiJson", method = RequestMethod.GET)
    public LayuiDataTableResultBean getNzEmployListLayuiJson(HttpServletRequest request, HttpServletResponse response, DUserResume user) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String flowid = request.getParameter("flowid").trim();

            Map<String, Object> _map = new HashMap<String, Object>();
            _map.put("agefrom", request.getParameter("agefrom").trim());
            _map.put("ageto", request.getParameter("ageto").trim());
            _map.put("workyearfrom", request.getParameter("workyearfrom").trim());
            _map.put("workyearto", request.getParameter("workyearto").trim());
            _map.put("heightfrom", request.getParameter("heightfrom").trim());
            _map.put("heightto", request.getParameter("heightto").trim());

            Map<String, Object> map = szService.getResumes(page, limit, user, _map);

            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            JSONArray jsonArray = new JSONArray();
            int num = 1;
            if (pageCount != 0) {
                Object object = map.get("list");
                for (DUserResume _user : (List<DUserResume>) object) {
                    JSONObject jsonObject = new JSONObject();
                    NZResume nzResume = nzService.getResumeByCardno(_user.getCardno().toString());
                    if(nzResume != null){
                        jsonObject.put("JOBNUMBER", (nzResume.getCode()==null?"":nzResume.getCode()));
                        jsonObject.put("GROUPDATE", (nzResume.getGroupdate()==null?"":nzResume.getGroupdate()));
                    }else {
                        jsonObject.put("JOBNUMBER", "");
                        jsonObject.put("GROUPDATE", "");
                    }
                    jsonObject.put("id_cb", "cb_" +_user.getId() );
                    jsonObject.put("id", limit * (page - 1) + num);
                    jsonObject.put("NAME", _user.getName());
                    jsonObject.put("CODE", _user.getCode());
                    jsonObject.put("JNAME", _user.getJname());
                    jsonObject.put("ContextPath", request.getContextPath() + "/UserResume/ViewDResume?id=" + _user.getId());
                    jsonObject.put("CARDNO", _user.getCardno());
                    jsonObject.put("EDUCATIONNAME", (_user.getEducationname() == null ? "" : _user.getEducationname()));
                    jsonObject.put("WORKEXPERIENCE", (_user.getWorkexperience() == null ? "" : _user.getWorkexperience()));
                    jsonObject.put("TEL", _user.getTel());
                    jsonObject.put("BDTIME", (_user.getBdtime() == null ? "" : _user.getBdtime()));
                    jsonObject.put("BDADRESS", (_user.getBdaddress() == null ? "" : _user.getBdaddress()));
                    jsonObject.put("BDLXRs", (_user.getBdlxr() == null ? "" : (_user.getBdlxr() + " " + _user.getBdlxdh())));
                    jsonObject.put("BDMSG", _user.getBdmsg());
                    jsonObject.put("BDBZ", (_user.getBdremark() == null ? "" : _user.getBdremark()));

                    if (_user.getOp5() == null || _user.getOp5().equals("未公布")) {
                        jsonObject.put("STATEb", "未公布");
                    } else {
                        jsonObject.put("STATEb", "已公布");
                    }

                    if (_user.getFqstate().equals("已放弃") && _user.getFqfid().equals(flowid)) {
                        jsonObject.put("STATEc", "已放弃");
                    } else {
                        if (_user.getNrid() != null) {
                            jsonObject.put("STATEc", "已推荐");
                        } else {
                            if (_user.getBdstate().equals("已报到")) {
                                jsonObject.put("STATEc", "已完成");
                            } else {
                                jsonObject.put("STATEc", "未完成");
                            }
                        }
                    }

                    jsonObject.put("arrange", _user.getBdarrange());

                    jsonArray.add(jsonObject);
                    num++;
                }
            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount((int) allcount);
            result.setData(jsonArray);

            return result;
        } catch (Exception e) {
            e.printStackTrace();

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }


}
